#include "tcpDepthWorker.h"
#include "PointCloudGenerator.h"
#include "depthdataprocessor.h"
#include "singleton.h"

#include <qtcpsocket.h>
#include <QThread>
#include <QImage>
#include <QFile>
#include <QCoreApplication>
#include <QtConcurrent>

TcpDepthWorker::TcpDepthWorker(QObject *parent)
    : QObject{parent}, m_socket(nullptr)
{

}

TcpDepthWorker::~TcpDepthWorker()
{
    // 断开所有信号连接，避免在对象销毁过程中触发回调
    if (m_socket) {
        m_socket->disconnect();
        // 确保socket处于非活跃状态
        if (m_socket->state() != QAbstractSocket::UnconnectedState) {
            // 主动关闭连接
            m_socket->abort();  // 立即关闭，不等待数据传输完成
            // 或者使用更优雅的方式：
            // m_socket->disconnectFromHost();
            // m_socket->waitForDisconnected(3000); // 等待3秒
        }

        // 释放socket对象
        m_socket->deleteLater();
        m_socket = nullptr;
    }
}


void TcpDepthWorker::connectToServer(const QString &ip, quint16 port)
{
    if (m_socket)
    {
        qDebug() << "socket status" << m_socket->state();
    }
    
    if (m_socket&&m_socket->state() == QAbstractSocket::ConnectedState)
    {
        emit stopConnectDepthTimer();
    }
    if (m_ip == ip && m_port == port && m_socket && m_socket->state() == QAbstractSocket::ConnectedState) {
        qDebug() << "已经连接到目标服务器，无需重复连接";
        return;
    }
    m_ip = ip;
    m_port = port;

    if (m_socket) {
        m_socket->deleteLater();
        m_socket = nullptr;
    }
    m_socket = new QTcpSocket();

    connect(m_socket, &QTcpSocket::connected, this, &TcpDepthWorker::connected);
    connect(m_socket, &QTcpSocket::disconnected, this, &TcpDepthWorker::disconnected);
    connect(m_socket, &QTcpSocket::readyRead, this, &TcpDepthWorker::onReadyRead);
    
    m_socket->connectToHost(ip, port);

    if (m_socket->waitForConnected(5000)) {
        qDebug() << "深度图--------连接成功";
        emit sendDepthConnectStatus(true);
    } else {
        emit errorOccurred(m_socket->errorString());
        emit sendDepthConnectStatus(false);
        qDebug() << "深度图--------连接失败" << m_socket->errorString();
    }
}

void TcpDepthWorker::sendData(const QByteArray &data)
{
    qDebug() << "TcpDepthWorker::sendData 当前线程：" << QThread::currentThreadId();
    qDebug() << "send Data" << data.toHex().toUpper();
    if (m_socket && m_socket->state() == QAbstractSocket::ConnectedState) {
        m_socket->write(data);
        m_socket->flush();
    } else {
        qWarning() << "Socket not connected. Cannot send data.";
    }
}

void TcpDepthWorker::onDisconnectSocket()
{
    if (m_socket->state() == QAbstractSocket::ConnectedState) {
        // 主动断开连接
        m_socket->disconnectFromHost();

        // 等待连接完全关闭（可选，超时后强制关闭）
        if (!m_socket->waitForDisconnected(3000)) { // 超时3秒
            qDebug() << "断开连接超时，强制关闭";
            m_socket->abort(); // 超时后强制关闭
        }
    }
}



void TcpDepthWorker::onReadyRead()
{
    qDebug() << "TcpDepthWorker::onReadyRead" << QThread::currentThreadId();
    QSharedPointer<QByteArray> data(new QByteArray(m_socket->readAll()));
    //QByteArray data = m_socket->readAll();
    //qDebug() << "data" << data;
    //processReceiveBuffer(data);
    emit newDataReceived(data);
    emit newCloudDataReceived(data);
}